const redis = require("redis");

module.exports = class Redis {
  static #client;
  static #user;
  static #password;
  static #host;

  static init(host, user, password) {
    this.#host = host;
    this.#user = user;
    this.#password = password;
  }

  static async getInstance() {
    if (!this.#client) {
      await Redis.connect();
    } else {
      // 旧的实例判断一下是否可以链接，不能就重新建一个
      try {
        await this.#client.ping();
      } catch (e) {
        await Redis.connect();
      }
    }
    return this.#client;
  }

  static async connect() {
    if (this.#host) {
      let params = {
        socket: { host: this.#host },
      };
      if (this.#password) {
        params.username = this.#user;
        params.password = this.#password;
      }
      this.#client = redis.createClient(params);
      await this.#client.connect();
    } else {
      throw new Error("Redis not init");
    }
  }

  static async exec(name, ...args) {
    let client = await Redis.getInstance();
    args.unshift(name);
    return await client.sendCommand(args);
  }

  static formatKey(name, params = {}) {
    let key = name;
    for (let nKey in params) {
      key += ":" + nKey + ":" + params[nKey];
    }
    return key;
  }
};
